package com.miui.theme.custom.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miui.theme.custom.data.ConfigDataStore
import com.miui.theme.custom.utils.MySQLHelper
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

data class ColumnDefinition(
    val name: String,
    val type: String,
    val length: String = "",
    val isPrimaryKey: Boolean = false,
    val isAutoIncrement: Boolean = false,
    val isNotNull: Boolean = false
) {
    fun toSqlString(): String {
        val typeStr = if (length.isNotBlank()) "$type($length)" else type
        val pk = if (isPrimaryKey) "PRIMARY KEY" else ""
        val nn = if (isNotNull) "NOT NULL" else ""
        val ai = if (isAutoIncrement) "AUTO_INCREMENT" else ""
        return "$name $typeStr $pk $nn $ai".trim().replace("  ", " ")
    }
}

val supportedDataTypes = listOf("INT", "VARCHAR", "TEXT", "DATE", "DATETIME", "DECIMAL", "BOOLEAN")

class CreateTableViewModel(configDataStore: ConfigDataStore) : ViewModel() {

    private val _createState = MutableStateFlow(DataState.Idle)
    val createState = _createState.asStateFlow()

    private val _error = MutableStateFlow<String?>(null)
    val error = _error.asStateFlow()

    private lateinit var helper: MySQLHelper
    private val initializationJob: Job

    init {
        initializationJob = viewModelScope.launch {
            val config = configDataStore.config.first()!!
            helper = MySQLHelper(config)
        }
    }

    fun createTable(tableName: String, columns: List<ColumnDefinition>) {
        if (tableName.isBlank() || columns.isEmpty()) {
            _error.value = "表名或字段列表不能为空"
            _createState.value = DataState.Error
            return
        }

        viewModelScope.launch {
            initializationJob.join()
            _createState.value = DataState.Loading

            val columnsSql = columns.joinToString(", ") { it.toSqlString() }
            val sql = "CREATE TABLE $tableName ($columnsSql)"

            val result = helper.executeUpdate(sql)
            if (result.isSuccess) {
                _createState.value = DataState.Success
            } else {
                _error.value = "创建失败: ${result.exceptionOrNull()?.message}"
                _createState.value = DataState.Error
            }
        }
    }
}